package beer.zivelin.awesome.walawala.mobile.ui;

import android.app.Activity;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.Toast;

import com.google.common.base.Stopwatch;

import java.util.List;
import java.util.concurrent.TimeUnit;

import beer.zivelin.awesome.walawala.mobile.R;
import beer.zivelin.awesome.walawala.mobile.Tester;
import beer.zivelin.awesome.walawala.mobile.entity.ApplicationData;
import beer.zivelin.awesome.walawala.mobile.service.ApplicationHelper;
import beer.zivelin.awesome.walawala.mobile.service.ApplicationLocator;

public class ApplicationViewHelper {

    /* define search_like_button status constants */
    //初始状态
    public static int SEARCH_LIKE_BUTTON_ST_INIT = 0;
    //普通搜索
    public static int SEARCH_LIKE_BUTTON_ST_NORMAL = 1;
    //模糊搜索
    public static int SEARCH_LIKE_BUTTON_ST_LIKE = 2;

    /* end of status constants */
    public static void drawAppOnView(List<ApplicationData> applicationInfoList, ViewGroup resultView, Activity activity) {
        Stopwatch stopwatch = Stopwatch.createStarted();
        LinearLayout line = null;
        for (int i = 0; i < applicationInfoList.size(); i++) {
            ApplicationData app = applicationInfoList.get(i);
            if (i % 3 == 0) {
                line = ApplicationViewHelper.generateAppViewLine(activity);
                resultView.addView(line);
            }

            View appImageView = ApplicationViewHelper.generateAppView(app, activity);
            line.addView(appImageView);
        }
        resultView.setTag(applicationInfoList);
        Log.w(Tester.TAG, "draw apps used " + stopwatch.elapsed(TimeUnit.MILLISECONDS) + " ms");
    }

    public static LinearLayout generateAppViewLine(Activity activity) {
        LinearLayout line = new LinearLayout(activity);
        line.setOrientation(LinearLayout.HORIZONTAL);
        line.setWeightSum(3f);

        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        int vertivalMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 6, activity.getResources().getDisplayMetrics());
        int horizontalMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 12, activity.getResources().getDisplayMetrics());
        layoutParams.setMargins(horizontalMargin, vertivalMargin, horizontalMargin, vertivalMargin);
        line.setLayoutParams(layoutParams);
        return line;
    }

    public static View generateAppView(ApplicationData app, Activity activity) {
        LinearLayout item = new LinearLayout(activity);
        item.setOrientation(LinearLayout.VERTICAL);
        int width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 0, activity.getResources().getDisplayMetrics());
        int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 72, activity.getResources().getDisplayMetrics());
        int vertivalMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2, activity.getResources().getDisplayMetrics());
        int horizontalMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2, activity.getResources().getDisplayMetrics());

        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(width, height, 1f);
        layoutParams.setMargins(horizontalMargin, vertivalMargin, horizontalMargin, vertivalMargin);
        item.setLayoutParams(layoutParams);

        ImageView appImageView = new ImageView(activity);
        appImageView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, 4));
        appImageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
        appImageView.setImageDrawable(app.getIcon());

        TextView appTextView = new TextView(activity);
        appTextView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        appTextView.setText(app.getName());
        appTextView.setGravity(Gravity.CENTER);

        item.addView(appImageView);
        item.addView(appTextView);

        item.setClickable(true);
        item.setOnClickListener((e) -> {
            ApplicationHelper.launch(app, activity);
        });
        item.setOnLongClickListener((e) -> {
            PopupMenu popupMenu = new PopupMenu(activity, item);
            popupMenu.getMenuInflater().inflate(R.menu.app_view_menu, popupMenu.getMenu());
            popupMenu.setOnMenuItemClickListener((menuItem) -> {
                if (menuItem.getItemId() == R.id.app_view_menu_uninstall) {
                    ApplicationHelper.directToAppUninstall(app, activity);
                } else if (menuItem.getItemId() == R.id.app_view_menu_details_settings) {
                    ApplicationHelper.directToAppDetailsSettings(app, activity);
                } else if (menuItem.getItemId() == R.id.app_view_menu_others) {
                    Toast.makeText(activity, "others to be coding...", Toast.LENGTH_LONG).show();
                }
                return true;
            });
            popupMenu.show();
            return true;
        });

        return item;
    }

    public static void clearSearchEditor(TextView t9SearchEditor, SearchEditorWatcher searchEditorWatcher) {
        if (t9SearchEditor.getText().length() > 0) {
            t9SearchEditor.setText("");
        } else {
            searchEditorWatcher.searchApp("");
        }
    }


    public static void initialT9Buttons(GridLayout buttonView, TextView t9SearchEditor, ViewGroup resultView, Activity activity) {
        Stopwatch stopwatch = Stopwatch.createStarted();
        setSearchLikeButtonStatus(activity.findViewById(R.id.bt_search_like), SEARCH_LIKE_BUTTON_ST_INIT);
        for (int i = 0; i < buttonView.getChildCount(); i++) {
            View child = buttonView.getChildAt(i);
            if (child instanceof Button) {
                String text = ((Button) child).getText().subSequence(0, 1).toString();
                if ("D".equals(text)) {
                    child.setOnClickListener(e -> {
                        String origin = t9SearchEditor.getText().toString();
                        if (origin.length() > 0) {
                            t9SearchEditor.setText(origin.substring(0, origin.length() - 1));
                            t9SearchEditor.setAutoSizeTextTypeWithDefaults(TextView.AUTO_SIZE_TEXT_TYPE_UNIFORM);
                        }
                    });
                    child.setLongClickable(true);
                    child.setOnLongClickListener(e -> {
                        t9SearchEditor.setText("");
                        return true;
                    });
                } else if ("W".equals(text)) {
                    child.setOnClickListener(e -> {
                        if (resultView.getTag() instanceof List) {
                            List applicationList = (List) resultView.getTag();
                            if (applicationList != null && applicationList.size() > 0) {
                                ApplicationHelper.launch((ApplicationData) applicationList.get(0), activity);
                            }
                        }
                    });
                } else {
                    child.setOnClickListener((e) -> {
                        //以按钮「0」为例，text内容会随着操作而变动，所以需要实时获取
                        String buttonText = ((Button) child).getText().subSequence(0, 1).toString();
                        if ("m".equals(buttonText)) {
                            t9SearchEditor.append(ApplicationLocator.LIKE_MODE_PREFIX);
                        } else {
                            t9SearchEditor.append(buttonText);
                        }
                        t9SearchEditor.setAutoSizeTextTypeWithDefaults(TextView.AUTO_SIZE_TEXT_TYPE_UNIFORM);
                    });
                    child.setOnLongClickListener(e -> {
                        List applicationList = (List) resultView.getTag();
                        int idx = Integer.parseInt(((Button) e).getText().toString().substring(0, 1)) - 1;
                        if (applicationList != null && applicationList.size() > 0 && idx >= 0 && idx < applicationList.size()) {
                            ApplicationHelper.launch((ApplicationData) applicationList.get(idx), activity);
                        }
                        return true;
                    });
                }
            }
        }
        Log.w(Tester.TAG, "initial buttons used " + stopwatch.elapsed(TimeUnit.MILLISECONDS) + " ms");
    }


    public static void setSearchLikeButtonStatus(Button searchLikeBt, int status) {
        if (status == SEARCH_LIKE_BUTTON_ST_INIT) {
            searchLikeBt.setText("maybe");
        } else if (status == SEARCH_LIKE_BUTTON_ST_NORMAL) {
            searchLikeBt.setText("0");
        } else if (status == SEARCH_LIKE_BUTTON_ST_LIKE) {
            searchLikeBt.setText("?");
        }
    }
}
